import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:chathouse/constant/my_color.dart';
import 'package:chathouse/util/base_utils.dart';
import 'package:flutter/material.dart';

import '../constant/res.dart';

enum ImageType { ASSET, FILE, NETWORK }

enum PackageName { BASE, DEFAULT }

///圖片工具類
class ImageUtils {
  ///svg圖片 默認加載本地資源
  static Widget image(String url,
      {Color? color,
      PackageName packageName = PackageName.DEFAULT,
      ImageType imageType = ImageType.ASSET,
      double radius = 0,
      double? height,
      double? width,
      double alpha = 1,
      BoxFit? fit,
      Key? key}) {
    var packageStr = _getPackStr(packageName);

    Widget widget;
    switch (imageType) {
      case ImageType.FILE:
        widget = Image.file(
          File(url),
          fit: _getBoxFit(height, width, fit),
          height: height,
          width: width,
        );
        break;
      case ImageType.NETWORK:
        widget = CachedNetworkImage(
            imageUrl: url,
            width: width,
            height: height,
            key: key,
            fit: _getBoxFit(height, width, fit),
            placeholder: (context, url) =>
                SizedBox(height: height, width: width),
            errorWidget: (context, url, error) {
              return Container(
                height: height,
                width: width,
                color: MyColors.gary_230230230,
              );
            });
        break;
      default:
        widget = Image.asset(url,
            package: packageStr,
            fit: _getBoxFit(height, width, fit),
            height: height,
            width: width,
            color: color);
        break;
    }
    if (radius != 0) {
      widget = ClipRRect(
        borderRadius: BorderRadius.circular(radius),
        child: widget,
      );
    }
    if (alpha < 1) widget = widget.setAlpha(alpha);
    return widget;
  }

  static BoxFit _getBoxFit(double? height, double? width, BoxFit? fit) {
    if (fit != null) {
      return fit;
    }
    if (width != null && height != null) {
      return BoxFit.cover;
    }
    if (width != null) {
      return BoxFit.fitWidth;
    }
    if (height != null) {
      return BoxFit.fitHeight;
    }
    return BoxFit.cover;
  }

  static String? _getPackStr(PackageName name) {
    switch (name) {
      case PackageName.BASE:
        return "base";
      case PackageName.DEFAULT:
        return null;
    }
  }
}
